package com.culturalCenter.dataCenter.service.impl.training;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.culturalCenter.dataCenter.Utils.ClassUtil;
import com.culturalCenter.dataCenter.Utils.DateFormatUtil;
import com.culturalCenter.dataCenter.Utils.TimeUtil;
import com.culturalCenter.dataCenter.customEntity.CustomServicedNumber;
import com.culturalCenter.dataCenter.customEntity.CustomServicedNumberList;
import com.culturalCenter.dataCenter.customEntity.activity.pull.ActivityResourceEntity;
import com.culturalCenter.dataCenter.customEntity.responseParam.training.TrainingInfoDetailResponse;
import com.culturalCenter.dataCenter.customEntity.responseParam.training.TrainingListResponse;
import com.culturalCenter.dataCenter.customEntity.responseParam.training.TrainingMenuResponse;
import com.culturalCenter.dataCenter.customEntity.training.*;
import com.culturalCenter.dataCenter.entity.activity.ActivityResource;
import com.culturalCenter.dataCenter.entity.training.*;
import com.culturalCenter.dataCenter.enums.StatusEnum;
import com.culturalCenter.dataCenter.mapper.training.*;
import com.culturalCenter.dataCenter.param.TrainingClassParam;
import com.culturalCenter.dataCenter.service.training.TrainingService;
import com.culturalCenter.dataCenter.vo.ActivityEventVo;
import com.culturalCenter.dataCenter.vo.TrainingClassVo;
import com.culturalCenter.dataCenter.vo.TrainingDatartVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : weicai
 * @date : 11:02 2020/9/22
 */
@Service
@Slf4j
public class TrainingServiceImpl implements TrainingService {
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private TrainingMonthCountMapper trainingMonthCountMapper;
    @Resource
    private TrainingDepartmentStatisticsMapper trainingDepartmentStatisticsMapper;
    @Resource
    private TrainingTodayMapper trainingTodayMapper;
    @Resource
    private TrainingPushMapper trainingPushMapper;
    @Resource
    private TrainingHostMapper trainingHostMapper;
    @Resource
    private TrainingTypeCountMapper trainingTypeCountMapper;
    @Resource
    private TrainingClientCountMapper trainingClientCountMapper;
    @Resource
    private TrainingTodayCountMapper trainingTodayCountMapper;
    @Resource
    private TrainingProjectMapper trainingProjectMapper;
    @Resource
    private TrainingMapper trainingMapper;
    @Resource
    private TrainingPeriodsMapper trainingPeriodsMapper;
    @Resource
    private TrainingAttendanceMapper trainingAttendanceMapper;
    @Resource
    private TrainingCommentCountMapper trainingCommentCountMapper;
    @Resource
    private TrainingTimeIntervalMapper trainingTimeInterValMapper;
    @Resource
    private TrainingAudienceCountMapper trainingAudienceCountMapper;
    @Resource
    private TrainingInfoCountMapper trainingInfoCountMapper;
    @Resource
    private TrainingApplyMapper trainingApplyMapper;

    @Override
    public TrainingMenuResponse getTrainingMenu(String branchId, String startDate, String endDate,String type) {
        TrainingMenuResponse trainingMenuResponse = new TrainingMenuResponse();
        // 本年培训总数
        TrainingMonthCount sum = trainingMonthCountMapper.selectAllTrainings(branchId,type);
        if (Objects.nonNull(sum)) {
            trainingMenuResponse.setTrainingNum(sum.getSum());
        }
        // 本月培训数
        TrainingMonthCount monthCount = trainingMonthCountMapper.selectTrainingsByMonth(DateFormatUtil.formatMonth(new Date()), branchId);
        if (Objects.nonNull(monthCount)) {
            trainingMenuResponse.setMonthNum(monthCount.getMonthIncreaseNum());
        }
        // 今日培训数
        TrainingMonthCount todayCount = trainingMonthCountMapper.selectTrainingsByDate(DateFormatUtil.format(new Date()), branchId);
        if (Objects.nonNull(todayCount)) {
            trainingMenuResponse.setTodayNum(todayCount.getTodayIncreaseNum());
        }
        TrainingClassParam trainingClassParam = trainingMapper.selectTrainingClassNum(branchId);
        trainingMenuResponse.setYearClassNums(trainingClassParam.getYearClassNum());
        trainingMenuResponse.setMonthClassNums(trainingClassParam.getMonthClassNum());
        trainingMenuResponse.setTodayClassNums(trainingClassParam.getDayClassNum());
        if(StringUtils.isBlank(type)){
            trainingMenuResponse.setAvgParticipationRate(trainingMapper.getTrainingAvgParticipationRate(branchId));
        }
        // 本月新增培训(曲线)
        List<CustomDayTotal> trainingMonthCounts = trainingMonthCountMapper.selectMonthNewlyAdded(branchId);
        if (CollectionUtils.isNotEmpty(trainingMonthCounts)) {
            trainingMenuResponse.setDayTotalList(trainingMonthCounts);
        }
        List<TrainingClassVo> trainingClassVos = trainingMapper.selectMothTrainClassNum(branchId);
        LocalDate date = LocalDate.now();
        LocalDate firstDayOfMonth = date.withDayOfMonth(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        while (date.isAfter(firstDayOfMonth) || date.isEqual(firstDayOfMonth)){
            String format = date.format(formatter);
            boolean allContainDate = trainingClassVos.stream()
                    .anyMatch(TrainingClassVo -> TrainingClassVo.getBeginTime().equals(format));
            if (!allContainDate){
                TrainingClassVo vo = new TrainingClassVo();
                vo.setBeginTime(format);
                vo.setTrainClassNum(0);
                trainingClassVos.add(vo);
            }
            date = date.minusDays(1);
        }
        TimeUtil.timeSort(trainingClassVos,TrainingClassVo::getBeginTime,"yyyy-MM-dd");
        trainingMenuResponse.setTrainingClassVos(trainingClassVos);
        // 各部门举办培训数
        List<TrainingDepartmentStatistics> trainingNumList = trainingDepartmentStatisticsMapper.selectTrainingNumByMonth(startDate,endDate, branchId);
        if (CollectionUtils.isNotEmpty(trainingNumList)) {
            trainingMenuResponse.setTrainingNumList(trainingNumList);
        }
        // 各部门培训名额数/报名数/录取数/签到数数据统计
        List<TrainingDepartmentStatistics> trainingsNum = trainingDepartmentStatisticsMapper.selectTrainingsNumByMonth(startDate,endDate, branchId);
        if (CollectionUtils.isNotEmpty(trainingsNum)) {
            trainingMenuResponse.setTrainingsNumList(trainingsNum);
        }
        // 今日培训
        List<CustomTrainingToday> trainingTodayList = trainingTodayMapper.selectByDate(DateFormatUtil.format(new Date()), branchId);
        if (CollectionUtils.isNotEmpty(trainingTodayList)) {
            trainingMenuResponse.setTrainingTodayList(trainingTodayList);
        }
        // 热门培训排行榜
        List<TrainingHost> trainingHostList = trainingHostMapper.selectByMonth(startDate,endDate, branchId);
        if (CollectionUtils.isNotEmpty(trainingHostList)) {
            trainingHostList.forEach(val ->{
                double v = Double.parseDouble(Optional.ofNullable(val.getParticipationRate()).orElse("0"));
                double num = 1 - Math.exp(-v);
                DecimalFormat decimalFormat = new DecimalFormat("#.##");
                val.setParticipationRate(decimalFormat.format(num));
            });
            trainingMenuResponse.setPopularTrainingList(trainingHostList);
        }
        // 今日推荐
        List<Training> trainingPushList = trainingMapper.selectByDate(branchId);
        if (CollectionUtils.isNotEmpty(trainingPushList)) {
            trainingMenuResponse.setRecommendTodayList(trainingPushList);
        }
        // 本月各分类培训报名数
        List<TrainingTypeCount> thisMonthNum = trainingTypeCountMapper.findPageAll(DateFormatUtil.formatMonth(new Date()), branchId);
        if (CollectionUtils.isNotEmpty(thisMonthNum)) {
            trainingMenuResponse.setThisMonthList(thisMonthNum);
        }
        // 上月各分类培训报名数
        List<TrainingTypeCount> lastMonthNum = trainingTypeCountMapper.queryLastMonth(DateFormatUtil.formatMonth(new Date()), branchId);
        if (CollectionUtils.isNotEmpty(lastMonthNum)) {
            trainingMenuResponse.setLastMonthList(lastMonthNum);
        }
        // 培训报名时段占比
        List<TrainingTimeInterval> trainingTimeIntervalList = trainingTimeInterValMapper.findPageAll(startDate,endDate,branchId);
        if (CollectionUtils.isNotEmpty(trainingTimeIntervalList)) {
            int count = trainingTimeIntervalList.stream().mapToInt(TrainingTimeInterval::getNum).sum();
            trainingTimeIntervalList.forEach(trainingTimeInterval -> trainingTimeInterval.setSum(count));
            trainingMenuResponse.setIntervalList(trainingTimeIntervalList);
        }
        // 培训报名平台入口占比
        List<TrainingClientCount> trainingClientCountList = trainingClientCountMapper.findPageAll(startDate,endDate,branchId);
        if (CollectionUtils.isNotEmpty(trainingClientCountList)) {
            trainingMenuResponse.setPlatformsRatioList(trainingClientCountList);
        }
        // 培训参与率排行
        List<CustomParticipationRateRank> participationRateRankList = trainingMapper.getParticipationRateRank(startDate,endDate,branchId);
        if (CollectionUtils.isNotEmpty(participationRateRankList)) {
            trainingMenuResponse.setParticipationRateRankList(participationRateRankList);
        }
        // 培训分类参与率排行
        List<CustomParticipationRateRank> classifyParticipationRateRankList = trainingMapper.getClassifyParticipationRateRank(startDate,endDate,branchId);
        if (CollectionUtils.isNotEmpty(classifyParticipationRateRankList)) {
            trainingMenuResponse.setClassifyParticipationRateRankList(classifyParticipationRateRankList);
        }
        // 可选时间段
        trainingMenuResponse.setEarliestDate(DateUtil.format(trainingMapper.getEarliestDate(), "yyyy-MM-dd"));
        trainingMenuResponse.setLatestDate(DateUtil.today());
        // 服务人群
        Set<String> crowdSet = new HashSet<>();
        List<String> crowdList = trainingMapper.getCrowd(branchId, startDate, endDate);
        if (CollectionUtils.isNotEmpty(crowdList)) {
            crowdList.forEach(a -> {
                if (StringUtils.isNotEmpty(a)) {
                    String[] b = a.split(",");
                    Arrays.stream(b).distinct().forEach(bb -> {
                        if (ObjectUtil.isNotEmpty(bb)) {
                            crowdSet.add(bb);
                        }
                    });
                }
            });
            Map<String, Integer> crowdMap = new HashMap<>();
            crowdSet.forEach(crowd -> crowdMap.put(crowd, trainingMapper.getNumByCrowd(branchId, crowd, startDate, endDate)));
            trainingMenuResponse.setCrowdMap(crowdMap);
        }
        // 艺术分类
        Set<String> artSet = new HashSet<>();
        List<String> artList = trainingMapper.getArt(branchId, startDate, endDate);
        if (CollectionUtils.isNotEmpty(artList)) {
            artList.forEach(a -> {
                if (StringUtils.isNotEmpty(a)) {
                    String[] b = a.split("、");
                    Arrays.stream(b).distinct().forEach(bb -> {
                        if (ObjectUtil.isNotEmpty(bb)) {
                            artSet.add(bb);
                        }
                    });
                }
            });
            Map<String, Integer> artMap = new HashMap<>();
            artSet.forEach(art -> artMap.put(art, trainingMapper.getNumByArt(branchId, art, startDate, endDate)));
            trainingMenuResponse.setArtClassificationMap(artMap);
        }
        // 服务人次：没传日期就查当前月的
        List<CustomServicedNumberList> dayServiceNumber = new ArrayList<>();
        Date startDay = DateUtil.parse(ObjectUtil.isEmpty(startDate) ? DateUtil.formatDateTime(DateUtil.beginOfMonth(DateUtil.date())) : startDate, "yyyy-MM-dd");
        Date endDay = DateUtil.parse(ObjectUtil.isEmpty(endDate) ? DateUtil.today() : endDate, "yyyy-MM-dd");
        long difference = DateUtil.between(startDay, endDay, DateUnit.DAY);
        /*
          固定显示10条，没数据的显示为0
           10条及以下：全显示
           10条以上：取开始和结束日期，然后中间的等分取8条
         */
        if (difference < 10) {
            for (int i = 0; i < difference + 1; i++) {
                CustomServicedNumberList customServicedNumberList = new CustomServicedNumberList();
                customServicedNumberList.setDate(DateUtil.offsetDay(startDay, i).toDateStr());
                CustomServicedNumberList servicedNumber = trainingMapper.getServicedNumberList(branchId, DateUtil.offsetDay(startDay, i).toSqlDate());
                if (ObjectUtil.isNull(servicedNumber)) {
                    customServicedNumberList.setOfflineNumber(0);
                    customServicedNumberList.setOnlineNumber(0);
                } else {
                    customServicedNumberList.setOfflineNumber(servicedNumber.getOfflineNumber());
                    customServicedNumberList.setOnlineNumber(servicedNumber.getOnlineNumber());
                }
                dayServiceNumber.add(customServicedNumberList);
            }
        } else {
            // 起始
            CustomServicedNumberList customServicedNumberList = new CustomServicedNumberList();
            customServicedNumberList.setDate(DateUtil.formatDate(startDay));
            CustomServicedNumberList servicedNumber = trainingMapper.getServicedNumberList(branchId, startDay);
            if (ObjectUtil.isNull(servicedNumber)) {
                customServicedNumberList.setOfflineNumber(0);
                customServicedNumberList.setOnlineNumber(0);
            } else {
                customServicedNumberList.setOfflineNumber(servicedNumber.getOfflineNumber());
                customServicedNumberList.setOnlineNumber(servicedNumber.getOnlineNumber());
            }
            dayServiceNumber.add(customServicedNumberList);
            // 中间
            for (int i = 1; i < 9; i++) {
                customServicedNumberList = new CustomServicedNumberList();
                customServicedNumberList.setDate(DateUtil.offsetDay(startDay, (int) ((difference + 1) / 10 * i)).toDateStr());
                servicedNumber = trainingMapper.getServicedNumberList(branchId, DateUtil.offsetDay(startDay, (int) ((difference + 1) / 10 * i)).toSqlDate());
                if (ObjectUtil.isNull(servicedNumber)) {
                    customServicedNumberList.setOfflineNumber(0);
                    customServicedNumberList.setOnlineNumber(0);
                } else {
                    customServicedNumberList.setOfflineNumber(servicedNumber.getOfflineNumber());
                    customServicedNumberList.setOnlineNumber(servicedNumber.getOnlineNumber());
                }
                dayServiceNumber.add(customServicedNumberList);
            }
            // 结束
            customServicedNumberList = new CustomServicedNumberList();
            customServicedNumberList.setDate(DateUtil.formatDate(endDay));
            servicedNumber = trainingMapper.getServicedNumberList(branchId, endDay);
            if (ObjectUtil.isNull(servicedNumber)) {
                customServicedNumberList.setOfflineNumber(0);
                customServicedNumberList.setOnlineNumber(0);
            } else {
                customServicedNumberList.setOfflineNumber(servicedNumber.getOfflineNumber());
                customServicedNumberList.setOnlineNumber(servicedNumber.getOnlineNumber());
            }
            dayServiceNumber.add(customServicedNumberList);
        }
        trainingMenuResponse.setServiceNumberList(dayServiceNumber);
        // 服务人次统计
        CustomServicedNumber servicedNumber = new CustomServicedNumber();
        CustomServicedNumber servicedNumber1 = trainingMapper.getServicedNumber(branchId, startDay, endDay);
        if (ObjectUtil.isNull(servicedNumber1)) {
            servicedNumber.setTotal(0);
            servicedNumber.setOnlineNumber(0);
            servicedNumber.setOfflineNumber(0);
        } else {
            servicedNumber = servicedNumber1;
        }
        trainingMenuResponse.setServicedNumber(servicedNumber);
        return trainingMenuResponse;
    }

    @Override
    public TrainingListResponse getTrainingList(String keywords, String status, String branchId, int pageNum, int pageSize) {
        TrainingListResponse trainingListResponse = new TrainingListResponse();
        List<TrainingTodayCount> trainingList = trainingTodayCountMapper.findTrainingList(branchId);
        if (CollectionUtils.isNotEmpty(trainingList)) {
            trainingList.forEach(t -> {
                if (t.getStatusName() != null && StatusEnum.SIGNINGUP.getStatus().equals(t.getStatusName())) {
                    trainingListResponse.setSigningUp(t.getNum());
                }
                if (t.getStatusName() != null && StatusEnum.PROCESSING.getStatus().equals(t.getStatusName())) {
                    trainingListResponse.setProcessing(t.getNum());
                }
                if (t.getStatusName() != null && StatusEnum.OVER.getStatus().equals(t.getStatusName())) {
                    trainingListResponse.setOver(t.getNum());
                }
            });
            //总数???
            trainingListResponse.setTotal(trainingList.stream().filter(t -> t.getStatusName() != null).mapToInt(TrainingTodayCount::getNum).sum());
        }
        //获取状态对应的数字：1，2，3
        Integer status1 = StatusEnum.getStatusId(status);
        PageHelper.startPage(pageNum, pageSize);
        List<CustomListTraining> customListTraining = trainingProjectMapper.getAllProjectAndTraining(keywords, status1, branchId);
        PageInfo<CustomListTraining> pageInfo = new PageInfo<>(customListTraining);
        trainingListResponse.setPageInfo(pageInfo);
        return trainingListResponse;
    }

    @Override
    public TrainingInfoDetailResponse getTrainingInfoDetail(String trainingId) {
        TrainingInfoDetailResponse trainingInfoDetailResponse = new TrainingInfoDetailResponse();
        Training training = trainingMapper.queryById(trainingId);
        if (Objects.nonNull(training)) {
            trainingInfoDetailResponse.setId(training.getRefId());
            trainingInfoDetailResponse.setDepartment(training.getDepartment());
            trainingInfoDetailResponse.setTrainingName(training.getTrainingName());
            if (training.getTrainingProject() != null) {
                trainingInfoDetailResponse.setProjectName(training.getTrainingProject().getProjectName());
            }
            trainingInfoDetailResponse.setPicture(training.getPicture());
            trainingInfoDetailResponse.setContact(training.getContacts());
            trainingInfoDetailResponse.setMobile(training.getMobile());
            trainingInfoDetailResponse.setOrganizationUnit(training.getOrganizationalUnit());
            //            trainingInfoDetailResponse.setLecturer(trainingPeriodsMapper.selectTeacher(trainingId));
            trainingInfoDetailResponse.setCrowd(training.getCrowd());
            trainingInfoDetailResponse.setTotalNum(training.getTotalNum());

            trainingInfoDetailResponse.setSexLimit(training.getSexLimit());
            if (training.getAgeLimit() == 1) {
                trainingInfoDetailResponse.setAgeMin(training.getAgeMin());
                trainingInfoDetailResponse.setAgeMax(training.getAgeMax());
            } else {
                trainingInfoDetailResponse.setAgeLimit(0);
            }
            trainingInfoDetailResponse.setTrainingType(training.getTrainingType());
            trainingInfoDetailResponse.setSignInType(training.getSignInType());
            trainingInfoDetailResponse.setAddress(training.getAddress());
            trainingInfoDetailResponse.setTotalPeriod(training.getTotalPeriod());
            trainingInfoDetailResponse.setPublishTime(training.getPublishTime());
            trainingInfoDetailResponse.setSignUpBeginTim(training.getSignUpBeginTime());
            trainingInfoDetailResponse.setSignUpEndTim(training.getSignUpEndTime());
            trainingInfoDetailResponse.setTrainingBeginTime(training.getTrainingBeginTime());
            trainingInfoDetailResponse.setTrainingEndTime(training.getTrainingEndTime());
            trainingInfoDetailResponse.setClassContent(training.getClassContent());
            if (ObjectUtil.isNotEmpty(training.getHours())) {
                Integer hour = training.getHours() / 60;
                Integer minute = training.getHours() % 60;
                trainingInfoDetailResponse.setHours(hour > 0 ? (minute > 0 ? (hour + "小时" + minute + "分钟") : (hour + "小时")) : (minute + "分钟"));
            } else {
                trainingInfoDetailResponse.setHours("无");
            }
        }
        // 获取培训课程全部期数
        List<CustomTrainingPeriods> trainingPeriodsList = trainingPeriodsMapper.queryAllByTrainingId(trainingId);
        if (CollectionUtils.isNotEmpty(trainingPeriodsList)) {
            trainingInfoDetailResponse.setPeriodsList(trainingPeriodsList);
        }
        return trainingInfoDetailResponse;
    }

    @Override
    public TrainingInfoDetailResponse getTrainingInfoTableDetail(String trainingId) {
        TrainingInfoDetailResponse response = trainingMapper.getTrainingInfoTableDetail(trainingId);
        if (ObjectUtil.isNotEmpty(response.getHours())) {
            Integer hour = Integer.parseInt(response.getHours()) / 60;
            int minute = Integer.parseInt(response.getHours()) % 60;
            response.setHours(hour > 0 ? (minute > 0 ? (hour + "小时" + minute + "分钟") : (hour + "小时")) : (minute + "分钟"));
        } else {
            response.setHours("无");
        }
        // 获取培训课程全部期数
        List<CustomTrainingPeriods> trainingPeriodsList = trainingPeriodsMapper.queryAllByTrainingId(trainingId);
        if (CollectionUtils.isNotEmpty(trainingPeriodsList)) {
            response.setPeriodsList(trainingPeriodsList);
        }
        return response;
    }

    @Override
    public CustomTrainingInfo getTrainingInfo(String trainingId) {
        CustomTrainingInfo trainingInfo = new CustomTrainingInfo();
        Training training = trainingMapper.queryTrainingInfoById(trainingId);
        if (Objects.nonNull(training)) {
            trainingInfo.setId(training.getRefId());
            trainingInfo.setPhoto(training.getPicture());
            trainingInfo.setTrainingName(training.getTrainingName());
            if (training.getTrainingProject() != null) {
                trainingInfo.setProjectName(training.getTrainingProject().getProjectName());
            }
            trainingInfo.setTrainingLabel(training.getTrainingLabel());
            trainingInfo.setStatus(trainingInfoCountMapper.selectTrainingStatus(trainingId));
            trainingInfo.setContacts(training.getContacts());
            trainingInfo.setPeriodsNum(training.getTotalPeriod());
            trainingInfo.setTrainingBeginTime(training.getTrainingBeginTime());
            trainingInfo.setTrainingEndTime(training.getTrainingEndTime());
        }
        // 人群特征
        List<CustomTrainingInfoStatistics> characteristicsList = trainingAudienceCountMapper.queryByTrainingId(trainingId);

        CustomTrainingInfoStatistics attendance = new CustomTrainingInfoStatistics();
        if (CollectionUtils.isNotEmpty(characteristicsList)) {

            List<CustomAge> ageIntervalList = trainingApplyMapper.queryAgeByTrainingId(trainingId);
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            if (CollectionUtils.isNotEmpty(ageIntervalList)) {
                // 获取报名年龄段最多的人数
                int max = ageIntervalList.stream().mapToInt(CustomAge::getSignUpNum).max().getAsInt();
                // 报名总数
                int sum = ageIntervalList.stream().mapToInt(CustomAge::getSignUpNum).sum();
                List<String> age = ageIntervalList.stream().filter(a -> a.getSignUpNum().equals(max)).map(CustomAge::getGeneration).collect(Collectors.toList());
                String rate = decimalFormat.format((float) max / sum * 100);

                characteristicsList.forEach(gender -> {
                    if (gender.getMaleNum() > gender.getFemaleNum()) {
                        gender.setMostGender("男");
                        gender.setMostGenderRate(gender.getMaleRate());
                    } else if (gender.getMaleNum() < gender.getFemaleNum()) {
                        gender.setMostGender("女");
                        gender.setMostGenderRate(gender.getFemaleRate());
                    } else {
                        gender.setMostGender("一样多");
                        gender.setMostGenderRate(gender.getMaleRate());
                    }
                    gender.setGenerationRate(rate);
                    for (int i = 0; i < age.size(); i++) {
                        gender.setGeneration(age.get(0));
                    }
//                    attendance.setParticipantsNum(gender.getWinningCount());

                });

            }
            trainingInfo.setCharacteristicsList(characteristicsList);
        }

        // 参与情况
        attendance.setAttendance100(trainingAttendanceMapper.selectAttendanceRate(trainingId));
        attendance.setAttendance90(trainingAttendanceMapper.selectAttendanceRate90(trainingId));
        attendance.setAttendance80(trainingAttendanceMapper.selectAttendanceRate80(trainingId));
        attendance.setElseAttendance(trainingAttendanceMapper.selectElseAttendanceRate(trainingId));
        attendance.setParticipantsNum(trainingAttendanceMapper.selectSignInNum(trainingId));
        trainingInfo.setAttendanceRate(attendance);

        // 点击数据
        List<TrainingInfoCount> browseList = trainingInfoCountMapper.selectBrowseNum(trainingId);
        if (CollectionUtils.isNotEmpty(browseList)) {
            trainingInfo.setBrowseList(browseList);
        }

        // 互动
        List<CustomInteractive> interactiveList = trainingCommentCountMapper.queryByTrainingId(trainingId);
        if (CollectionUtils.isNotEmpty(interactiveList)) {
            trainingInfo.setInteractiveList(interactiveList);
        }

        return trainingInfo;
    }

    @Override
    public List<TrainingDatartVo>getTrainingTable() {
        List<TrainingDatartVo> trainingTable = trainingMapper.getTrainingTable();
        trainingTable.stream().forEach(training -> {
            if(StringUtils.isNotBlank(training.getClassContent())) {
                String classContent = training.getClassContent();
                // 使用replaceAll方法将尖括号替换为空白
                String replacedContent = classContent.replaceAll("<[^>]+>|&nbsp;|&ldquo;|&rdquo;|&mdash;|★|●|\\n", "");
                // 将替换后的内容设置回对象的classContent属性
                training.setClassContent(replacedContent);
            }
        });
        return trainingTable;
    }

    @Override
    public Map getResource() {
        LocalDate currentDate = LocalDate.now();
        LocalDate lastMonthDate = currentDate.minusMonths(1);
        LocalDate lastSecondMonthDate = currentDate.minusMonths(2);
        List<ZiYuan> courseList = new ArrayList();

        int course  = trainingMapper.getCourse(currentDate.getYear(),currentDate.getMonthValue());
        ZiYuan thisMonth = new ZiYuan();
        thisMonth.setMonth(currentDate.getMonthValue());
        thisMonth.setCourse(course);


        int course1  = trainingMapper.getCourse(lastMonthDate.getYear(),lastMonthDate.getMonthValue());
        ZiYuan lastMonth = new ZiYuan();
        lastMonth.setMonth(lastMonthDate.getMonthValue());
        lastMonth.setCourse(course1);


        int course2  = trainingMapper.getCourse(lastSecondMonthDate.getYear(),lastSecondMonthDate.getMonthValue());
        ZiYuan lastSecondMonth = new ZiYuan();
        lastSecondMonth.setMonth(lastSecondMonthDate.getMonthValue());
        lastSecondMonth.setCourse(course2);


        TrainingMonthCount courseSum = trainingMonthCountMapper.selectAllTrainingsAll("577896166678151168");

        Map result = new HashMap();
        courseList.add(lastSecondMonth);
        courseList.add(lastMonth);
        courseList.add(thisMonth);
        result.put("courseSum",courseSum.getSum());
        result.put("courseList",courseList);

        // 获取本月第一天的零点
        LocalDateTime currentMonthFirstDay = LocalDateTime.of(currentDate.getYear(), currentDate.getMonth(), 1, 0, 0, 0);
        long currentMonthTimeStamp = currentMonthFirstDay.toInstant(ZoneOffset.UTC).toEpochMilli();

        // 获取上个月第一天的零点
        LocalDateTime lastMonthFirstDay = LocalDateTime.of(lastMonthDate.getYear(), lastMonthDate.getMonth(), 1, 0, 0, 0);
        long lastMonthTimeStamp = lastMonthFirstDay.toInstant(ZoneOffset.UTC).toEpochMilli();

        // 获取上上个月第一天的零点
        LocalDateTime lastSecondMonthFirstDay = LocalDateTime.of(lastSecondMonthDate.getYear(), lastSecondMonthDate.getMonth(), 1, 0, 0, 0);
        long lastSecondMonthTimeStamp = lastSecondMonthFirstDay.toInstant(ZoneOffset.UTC).toEpochMilli();

        List<ZiYuan> resourceList = new ArrayList();

        String url = "https://www.gz-arts.com/api/tcc-mes-service/client-api/culture/activity/listHighlights";
        Map<String, Object> param = new HashMap<>();
        param.put("updateTimestamp", currentMonthTimeStamp);
        param.put("size", 500);
        param.put("current", 1);
        JSONObject data = getResponse(url, param);
        Integer thisMonthNo = JSON.parseObject(data.getString("total"), Integer.class);
        ZiYuan thisMonth1 = new ZiYuan();
        thisMonth1.setMonth(currentDate.getMonthValue());
        thisMonth1.setCourse(thisMonthNo);

        param.put("updateTimestamp", lastMonthTimeStamp);
        JSONObject data1 = getResponse(url, param);
        Integer lastMonthNo = JSON.parseObject(data1.getString("total"), Integer.class);
        ZiYuan lastMonth1 = new ZiYuan();
        lastMonth1.setMonth(lastMonthDate.getMonthValue());
        lastMonth1.setCourse( lastMonthNo - thisMonthNo );

        param.put("updateTimestamp", lastSecondMonthTimeStamp);
        JSONObject data2 = getResponse(url, param);
        Integer lastSecondMonthNo = JSON.parseObject(data2.getString("total"), Integer.class);
        ZiYuan lastSecondMonth1 = new ZiYuan();
        lastSecondMonth1.setMonth(lastSecondMonthDate.getMonthValue());
        lastSecondMonth1.setCourse( lastSecondMonthNo- lastMonthNo );


        param.remove("updateTimestamp");
        JSONObject data3 = getResponse(url, param);
        Integer resourceSum = JSON.parseObject(data3.getString("total"), Integer.class);

        resourceList.add(lastSecondMonth1);
        resourceList.add(lastMonth1);
        resourceList.add(thisMonth1);
        result.put("resourceSum",resourceSum);
        result.put("resourceList",resourceList);
        return result;
    }
    public JSONObject getResponse(String url, Map<String, Object> param) {
        try {
            String interfaceUrl = url + "?" + ClassUtil.setParamString(param);
            String responseJson = restTemplate.getForObject(interfaceUrl, String.class, param);
            String data = JSON.parseObject(responseJson).getString("data");
            return JSON.parseObject(data);
        } catch (HttpServerErrorException e) {
            log.error("TCC综合管理平台服务端异常，请联系TCC相关人员");
            throw e;
        }
    }
}
